﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Multiprocessing.Core.Units
{
    public class TaskProcessingUnit : BaseProcessingUnit
    {
        #region Fields

        private Task _task;
        private bool _disposed;
        private readonly CancellationTokenSource _cancellationTokenSource;

        #endregion

        #region Constructors

        public TaskProcessingUnit()
        {
            _disposed = false;
            _cancellationTokenSource = new CancellationTokenSource();
        }

        #endregion

        #region Properties

        public override bool IsRunning
        {
            get { return !ReferenceEquals(_task, null) && _task.Status == TaskStatus.Running; }
        }

        #endregion

        #region Methods

        public override void Start()
        {
            _task = Task.Factory.StartNew(Action, _cancellationTokenSource.Token);
            _task.ContinueWith(t => OnFinished());
        }

        public override void ForceStop()
        {
            _cancellationTokenSource.Cancel();
            _task.Wait();
        }

        public override void Wait()
        {
            _task.Wait();
        }

        protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _task.Dispose();
                }
                _disposed = true;
            }
            base.Dispose(disposing);
        }
        
        #endregion
    }
}
